import { defineStore } from 'pinia'
import { apiClient } from '@/utils/api-client'
import type { User as ApiUser, UserProfile as ApiUserProfile, UserSettings as ApiUserSettings } from '@/utils/api-client'

export interface UserProfile {
  id: string
  nickname?: string
  avatarUrl?: string
  createdAt: string
  updatedAt: string
}

export interface UserSettings {
  id: string
  theme: 'LIGHT' | 'DARK' | 'AUTO'
  searchEngine: 'GOOGLE' | 'BING' | 'BAIDU' | 'DUCKDUCKGO'
  backgroundType: 'GRADIENT' | 'IMAGE' | 'COLOR'
  backgroundValue?: string
  showBookmarks: boolean
  showWeather: boolean
  showTime: boolean
  language: string
  createdAt: string
  updatedAt: string
}

interface User {
  id: string
  email: string
  emailVerified: boolean
  createdAt: string
}

interface AuthState {
  user: User | null
  loading: boolean
  initialized: boolean
  profile: UserProfile | null
  settings: UserSettings | null
}

interface AuthResult {
  success: boolean
  data?: any
  error?: string
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    user: null,
    loading: false,
    initialized: false,
    profile: null,
    settings: null
  }),

  getters: {
    isAuthenticated: (state: AuthState) => !!state.user,
    userEmail: (state: AuthState) => state.user?.email || '',
    userId: (state: AuthState) => state.user?.id || '',
    userMetadata: (state: AuthState) => state.user?.user_metadata || {}
  },

  actions: {
    // 初始化认证状态
    async initAuth() {
      try {
        this.loading = true
        
        // 检查是否有有效的访问令牌
        if (apiClient.isAuthenticated()) {
          try {
            // 验证令牌并获取用户信息
            const response = await apiClient.getCurrentUser()
            this.user = {
              id: response.user.id,
              email: response.user.email,
              emailVerified: response.user.emailVerified,
              createdAt: response.user.createdAt
            }
            
            // 设置用户资料和设置
            if (response.user.profile) {
              this.profile = {
                id: response.user.profile.id,
                nickname: response.user.profile.nickname,
                avatarUrl: response.user.profile.avatarUrl,
                createdAt: response.user.profile.createdAt,
                updatedAt: response.user.profile.updatedAt
              }
            }
            
            if (response.user.settings) {
              this.settings = {
                id: response.user.settings.id,
                theme: response.user.settings.theme,
                searchEngine: response.user.settings.searchEngine,
                backgroundType: response.user.settings.backgroundType,
                backgroundValue: response.user.settings.backgroundValue,
                showBookmarks: response.user.settings.showBookmarks,
                showWeather: response.user.settings.showWeather,
                showTime: response.user.settings.showTime,
                language: response.user.settings.language,
                createdAt: response.user.settings.createdAt,
                updatedAt: response.user.settings.updatedAt
              }
            }
          } catch (error) {
            console.error('验证令牌失败:', error)
            // 清除无效令牌
            this.clearUserData()
          }
        }

        this.initialized = true
      } catch (error) {
        console.error('初始化认证失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 邮箱登录
    async signInWithEmail(email: string, password: string): Promise<AuthResult> {
      try {
        this.loading = true
        
        const response = await apiClient.login(email, password)
        
        // 设置用户信息
        this.user = {
          id: response.user.id,
          email: response.user.email,
          emailVerified: response.user.emailVerified,
          createdAt: response.user.createdAt
        }
        
        // 获取用户数据
        await this.fetchUserData()
        
        return { success: true, data: response }
      } catch (error: any) {
        console.error('登录失败:', error)
        return { success: false, error: error.message }
      } finally {
        this.loading = false
      }
    },

    // 邮箱注册
    async signUpWithEmail(email: string, password: string, metadata: Record<string, any> = {}): Promise<AuthResult> {
      try {
        this.loading = true
        
        const response = await apiClient.register(email, password, metadata.nickname)
        
        // 注册成功后设置用户信息
        this.user = {
          id: response.user.id,
          email: response.user.email,
          emailVerified: response.user.emailVerified,
          createdAt: response.user.createdAt
        }
        
        // 获取用户数据
        await this.fetchUserData()

        return {
          success: true,
          data: response
        }
      } catch (error: any) {
        return {
          success: false,
          error: error.message || '注册失败'
        }
      } finally {
        this.loading = false
      }
    },

    // 第三方登录 (暂不支持)
    async signInWithProvider(provider: string): Promise<AuthResult> {
      return {
        success: false,
        error: '第三方登录功能暂不支持'
      }
    },

    // 登出
    async signOut(): Promise<AuthResult> {
      try {
        this.loading = true
        
        await apiClient.logout()
        this.clearUserData()
        
        return { success: true }
      } catch (error: any) {
        console.error('登出失败:', error)
        return { success: false, error: error.message }
      } finally {
        this.loading = false
      }
    },

    // 重置密码 (暂不支持)
    async resetPassword(email: string): Promise<AuthResult> {
      return {
        success: false,
        error: '重置密码功能暂不支持'
      }
    },

    // 更新用户资料 (已迁移到updateUserProfile)
    async updateProfile(updates: Record<string, any>): Promise<AuthResult> {
      try {
        const success = await this.updateUserProfile(updates)
        return { success }
      } catch (error: any) {
        return { success: false, error: error.message }
      }
    },

    // 获取用户数据
    async fetchUserData(): Promise<void> {
      if (!this.user) return
      
      try {
        const response = await apiClient.getCurrentUser()
        
        // 设置用户资料
        if (response.user.profile) {
          this.profile = {
            id: response.user.profile.id,
            nickname: response.user.profile.nickname,
            avatarUrl: response.user.profile.avatarUrl,
            createdAt: response.user.profile.createdAt,
            updatedAt: response.user.profile.updatedAt
          }
        }
        
        // 设置用户设置
        if (response.user.settings) {
          this.settings = {
            id: response.user.settings.id,
            theme: response.user.settings.theme,
            searchEngine: response.user.settings.searchEngine,
            backgroundType: response.user.settings.backgroundType,
            backgroundValue: response.user.settings.backgroundValue,
            showBookmarks: response.user.settings.showBookmarks,
            showWeather: response.user.settings.showWeather,
            showTime: response.user.settings.showTime,
            language: response.user.settings.language,
            createdAt: response.user.settings.createdAt,
            updatedAt: response.user.settings.updatedAt
          }
        }
      } catch (error) {
        console.error('获取用户数据失败:', error)
      }
    },

    // 获取用户资料 (已迁移到fetchUserData)
    async fetchUserProfile(): Promise<UserProfile | null> {
      await this.fetchUserData()
      return this.profile
    },

    // 获取用户设置 (已迁移到fetchUserData)
    async fetchUserSettings(): Promise<UserSettings | null> {
      await this.fetchUserData()
      return this.settings
    },

    // 更新用户资料
    async updateUserProfile(updates: Partial<UserProfile>): Promise<boolean> {
      if (!this.user) return false
      
      try {
        console.log('正在更新用户资料:', updates, '用户ID:', this.user.id)
        
        const response = await apiClient.updateUserProfile(updates)
        
        console.log('资料更新成功:', response)

        // 重新获取用户数据
        await this.fetchUserData()
        return true
      } catch (error) {
        console.error('更新用户资料失败:', error)
        return false
      }
    },

    // 更新用户设置
    async updateUserSettings(updates: Partial<UserSettings>): Promise<boolean> {
      if (!this.user) return false
      
      try {
        const response = await apiClient.updateUserSettings(updates)
        
        console.log('设置更新成功:', response)

        // 重新获取用户数据
        await this.fetchUserData()
        return true
      } catch (error) {
        console.error('更新用户设置失败:', error)
        return false
      }
    },

    // 清除用户数据
    clearUserData() {
      this.user = null
      this.profile = null
      this.settings = null
      
      // 清除其他 store 的用户相关数据
      // 这里可以调用其他 store 的清除方法
    },

    // 别名方法，兼容登录页面调用
    async login(email: string, password: string) {
      const result = await this.signInWithEmail(email, password)
      if (!result.success) {
        // 提供更友好的错误信息
        let errorMessage = result.error || '登录失败'
        if (result.error?.includes('Invalid login credentials')) {
          errorMessage = '邮箱或密码错误，请检查后重试'
        } else if (result.error?.includes('Email not confirmed')) {
          errorMessage = '请先验证您的邮箱地址'
        } else if (result.error?.includes('Too many requests')) {
          errorMessage = '登录尝试次数过多，请稍后再试'
        }
        throw new Error(errorMessage)
      }
      return result
    },

    async signup(email: string, password: string, metadata?: { nickname?: string }) {
      const result = await this.signUpWithEmail(email, password, metadata || {})
      if (!result.success) {
        // 提供更友好的错误信息
        let errorMessage = result.error || '注册失败'
        if (result.error?.includes('User already registered')) {
          errorMessage = '该邮箱已被注册，请直接登录或使用其他邮箱'
        } else if (result.error?.includes('Password should be at least')) {
          errorMessage = '密码长度至少需要6位字符'
        } else if (result.error?.includes('Unable to validate email address')) {
          errorMessage = '邮箱格式不正确，请检查后重试'
        }
        throw new Error(errorMessage)
      }
      return result
    },

    async loginWithProvider(provider: string) {
      const result = await this.signInWithProvider(provider)
      if (!result.success) {
        throw new Error(result.error || '登录失败')
      }
      return result
    },

    async logout() {
      const result = await this.signOut()
      if (!result.success) {
        throw new Error(result.error || '退出失败')
      }
      return result
    }
  }
})